<template>
  <div>
    <el-col :span="24" class="bg1">
      <div class="grid-content bg-purple">
        <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" :isSubmitBtn="false" />
      </div>
    </el-col>
    <el-col :span="24" class="bg2">
      <BreakSpace label="活动完成情况列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>

      <FilterTable
        :isExportExcel="false"
        exportFileName="vin数据.xlsx"
        :onCalcExportData="handleExportFun"
        ref="table"
        height="200"
        :onSyncTableData="vinTableChangeFun"
        selectionType="single"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchapiVin"
        :params="fetchParamsVin"
        datakey="records"
        columnsRef="yxqPjxmTable"
        :isColumnFilter="true"
        :onColumnsChange="columns => (this.columns = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
      <template slot="controls">
          <el-button size="small" :disabled="disableState || addBtnDisabled" type="primary" icon="el-icon-download" @click="downHandle">明细下载</el-button>
      </template>

      </FilterTable>
    </el-col>

    <div class="dialogBottmView">
      <el-button size="small" type="primary" class="btnStyle" @click="closeMenu('3')">关闭 </el-button>
    </div>
  </div>
</template>

<script>
import {  getByMaId, } from '@/api/repair/batchEventManagement/activityDistribution';

import { exportByMaId } from '@/api/repair/batchEventManagement/activityQueryCDuan';
import {getExecutionStatusDetail,getExecutionStatusForExport } from '@/api/repair/batchEventManagement/activityExecutionStatusQueryCDuan';

import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';

import { dictionary } from '@/utils/dictMixin';
import { isEmpty } from '@/utils/utils';
import { exportExcelFile } from '@/utils/index';
import config from '@/assets/js/config';


export default {
  name: 'detail',
  mixins: [dictionary, dealerMixin],
  /*handleType show   活动审核  show-1  索赔审核*/
  props: ['handleType', 'maId'],
  data() {
    this.saveData = null;
    return {
      uploadPrefix: config.uploadUrl,
      appendixName :'',
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      visibleVin: false,
      visibleSport: false,
      visiblePeij: false,
      visibleMainCode: false,
      fetchParams: { xhrAbort: true },
      fetchParamPeij: { xhrAbort: true },
      fetchParamSport: { xhrAbort: true },
      fetchParamSuopei: { xhrAbort: true },
      fetchApiPeij: '',
      fetchApi: '',
      fetchApiSport: '',
      fetchApiSuopei: '',
      fetchapiVin: getExecutionStatusDetail,
      fetchParamsVin: { xhrAbort: true },
      onChangeColumn: [],
      vinArr: [] /**/,
      sportArr: [],
      peijArr: [],
      fujArr:[],
      status: 1 /*1  表单选择  2 新建配件*/,
      detailObj: {},
      imageList: [],
      UploadFileIsShow: false,
      // actionUrl: '/api/dmscloud.activity/ttRpMa/uploadVinTem'//本地
      actionUrl: 'https://dcs-test-api.livanauto.com/api/dmscloud.activity/ttRpMa/uploadVinTem',//测试环境

    };
  },
  components: {},
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;

    // this.BaseSuopeiTable = this.$refs.tableSuopei.$refs.pageTable;

    // this.getAllDelears(this.columns, ['resDealer', 'updateCode', 'salesDealer'], 'table');

    this.getData();

    this.initSelect();

    this.getUnit();
  },
  methods: {
    async downHandle() {

      let params = {
        maId: this.maId
      };
      console.log(params, '导出::');
      let res = await getExecutionStatusForExport(params);

      console.log(res.data, '导出数据::');
      try {
        exportExcelFile(res.data, '活动完成情况列表');
      } catch (e) {
        console.log(e, '错误::');
      }

      // let params = {
      //   maId: this.maId
      // };
      // await this.downHandleFile(getExecutionStatusForExport, params, '活动完成情况列表');
    },
    cheageselect(data){
          console.log(data)
        this.txt.data

    },
    async getUnit() {
    },

    async initSelect() {
      // this.getAllUsers(this.columnSuopei, ['createdBy'], 'table');
    },

    handleExportFun(row) {
      row.vinStatus = this.createDictText(row.vinStatus, 6040);

      let oldResDealer = isEmpty(row['oldResDealer']) ? '' : row['oldResDealer'];
      let oldVinStatus = isEmpty(row['oldVinStatus']) ? '' : row['oldVinStatus'];

      let status = '';

      if (isEmpty(oldResDealer) && isEmpty(oldVinStatus)) {
        status = '否';
      } else {
        status = '是';
      }
      row.status = status;

      row.vinStatus = this.createDictText(row.vinStatus, 4021);
    },

    /*配置数量发生改变的时候执行*/
    onCellChange(e, obj) {
      let counts = isEmpty(obj['counts']) ? '0' : obj['counts'];
      let price = isEmpty(obj['price']) ? '0' : obj['price'];
      let amount = obj['amount'];

      let toatalCount = isEmpty(parseInt(counts) * parseInt(price)) ? '0' : parseInt(counts) * parseInt(price);

      obj['amount'] = toatalCount;

      this.BasePeijTable.DO_REFRESH(false);
    },

    /*导入*/
    importHandle() {
      this.handleType = 'import';
      this.UploadFileIsShow = true;
    },


    /*根据ID查询*/
    async getData() {
      let res = await getByMaId({ maId: this.maId });
      this.fetchParamsVin = Object.assign({}, this.fetchParamsVin, { maId: this.maId, xhrAbort: false });
      if (res.resultCode == 200 && res.success == true) {
        let data = isEmpty(res['data']) ? {} : res['data'];
         this.appendixName = data.appendixName;


        for (let i in data) {
          this.formList.map(x => {


            if (i == x.fieldName) {
              x.initialValue = x.fieldName === 'maStrategy'? Number(data[i]):data[i];//mo

            }
          });
        }
         this.appendixName = data.appendixName ? JSON.parse(data.appendixName) : [];
        this.appendixAddress = data.appendixAddress ? JSON.parse(data.appendixAddress) : [];


        // 数据组装
        const files = [];
        if (this.appendixName) {
          this.appendixName.forEach((name, index) => {
            //  findFileByUrl(this.appendixAddress[index]).then(res => {
            //   this.imageList.push({name: name,url: res.data});
            // });
           files.push({
              name,
              url: this.appendixAddress[index],
            });
          });

          // this.formList.find(item => item.fieldName === 'appendixAddress').initialValue = this.imageList;
          // 数据赋值
          this.formList.find((x) => {
            x.fieldName === 'appendixAddress' && (x.initialValue = files);
          });
        }

      }
    },

    peijTableChangeFun(val) {
      this.peijArr = val;
    },
    fujTableChangeFun(val) {
      this.fujArr = val;
    },

    vinTableChangeFun(val) {
      this.vinArr = val;

      val.forEach((item, index) => {
        let oldResDealer = isEmpty(item['oldResDealer']) ? '' : item['oldResDealer'];
        let oldVinStatus = isEmpty(item['oldVinStatus']) ? '' : item['oldVinStatus'];
        let status = '';
        if (isEmpty(oldResDealer) && isEmpty(oldVinStatus)) {
          status = '否';
        } else {
          status = '是';
        }
        item.status = status;
      });
    },

    sportTableChangeFun(val) {
      this.sportArr = val;
    },

    async closeMenu(type) {
      this.$emit('close');
    },
    closeDialog() {
      this.visibleVin = false;
      this.visibleSport = false;
      this.visiblePeij = false;
    },

    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '服务活动基本信息'
        },
        {
          type: 'INPUT',
          label: '活动编号：',
          fieldName: 'maNo',
          itemList: [],
          disabled: true,
          placeholder: '',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '活动名称：',
          fieldName: 'maTitle',
          disabled: true,
          rules: [{ required: false, trigger: 'change' }],
          placeholder: '请输入',
          initialValue: ''
        },
        {
          type: 'DATE',
          label: '活动开始日期：',
          fieldName: 'bDate',
          disabled: true,
          format: 'yyyy-MM-dd',
          placeholder: '请选择',
          rules: [{ required: false, trigger: 'change' }],
          initialValue: ''
        },

        {
          type: 'DATE',
          label: '活动截止日期：',
          fieldName: 'eDate',
          disabled: true,
          format: 'yyyy-MM-dd',
          placeholder: '请选择',
          rules: [{ required: false, trigger: 'change' }],
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '活动类型：',
          fieldName: 'maStrategy',
          placeholder: '请选择',
          disabled: true,
          // rules: [{ required: true, message: '请选择',trigger: 'change'}],
          itemList: this.createDictList('5080'),
          initialValue: ''

        },

        {
          type: 'TEXT_AREA',
          label: '活动说明',
          fieldName: 'maRemarks',
          placeholder: '请选择',
          disabled: true,
          rules: [{ required: false, trigger: 'change' }],
          initialValue: '',
          selfCols: 3
        },

        // {
        //   type: 'UPLOAD_FILE',
        //   label: '附件',
        //   disabled: true,
        //   fieldName: 'appendixAddress',
        //   disabled: true,
        //   initialValue: '',
        //   selfCols: 4,
        // }

      ];
    },

    //VIN列表
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          // width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '活动完成情况',
          dataIndex: 'completion',
          sorter: true,
          filter: true,
          filterType: 'input'
        }, {
          title: '维修工单号',
          dataIndex: 'roNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '责任站代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false

        },
        {
          title: '责任站简称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '服务中心代码',
          dataIndex: 'dealerCenterCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '服务中心简称',
          dataIndex: 'dealerCenterName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '活动完成日期',
          dataIndex: 'completeAt',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          filterType: 'date-range'
        },
      ];
    }
  }
};
</script>

<style scoped lang="less">
.bg1 {
  border: 1px solid @borderColor;
  border-radius: @borderRadius;
  box-shadow: @boxShadow;
  padding: @modulePadding;
  padding-left: 0;
  padding-top: 15px;
  padding-bottom: 15px;
}

.bg2 {
  margin-top: 10px;
  margin-bottom: 10px;
}

.btn {
  text-align: center;
}

.btnStyle {
  margin-top: 10px;
}
</style>
